package com.qiu.usercenter.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qiu.usercenter.common.BaseResponse;
import com.qiu.usercenter.common.ErrorCode;
import com.qiu.usercenter.common.ResultUtils;
import com.qiu.usercenter.model.domain.Question;
import com.qiu.usercenter.model.domain.User;
import com.qiu.usercenter.model.domain.request.ProblemGenerationRequest;
import com.qiu.usercenter.model.domain.request.UserLoginRequest;
import com.qiu.usercenter.service.QuestionService;
import com.qiu.usercenter.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import com.qiu.usercenter.model.domain.request.UserRegisterRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

import static com.qiu.usercenter.contant.UserConstant.ADMIN_ROLE;
import static com.qiu.usercenter.contant.UserConstant.USER_Login_STATE;


/**
 * 用户接口
 *
 * @author ：qiu
 */
@RestController
@RequestMapping("/user")
@Api(tags = "用户管理模块")

public class userController {

    @Resource
    private UserService userService;
    @Resource
    private QuestionService questionService;


    /**
     * 注册接口
     *
     * @param userRegisterRequest 注册请求体
     * @return 用户id
     */
    @PostMapping("/register")
    @ApiOperation(value = "注册功能")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        if (userRegisterRequest == null) {
            return ResultUtils.error(ErrorCode.PARAM_ERROR, "注册请求体为空");
        }
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        String plantcode = userRegisterRequest.getPlantcode();
        System.out.println(userAccount + " " + userPassword + " " + checkPassword + " " + plantcode);

        if (StringUtils.isAllBlank(userAccount, userPassword, checkPassword, plantcode)) {
            return ResultUtils.error(ErrorCode.PARAM_NOT_NULL);
        }

        Long id = userService.userRegister(userAccount, userPassword, checkPassword, plantcode);

//        return new BaseResponse<>(0, id, "注册成功");
        return ResultUtils.success(id);
    }

    /**
     * 登录接口
     *
     * @param UserLoginRequest 用户登录接口
     * @return 用户脱敏信息
     */
    @PostMapping("/login")
    @ApiOperation(value = "登录功能")
    public BaseResponse<User> userLogin(@RequestBody UserLoginRequest UserLoginRequest, HttpServletRequest request) {

        if (UserLoginRequest == null) {
            return ResultUtils.error(ErrorCode.PARAM_NOT_NULL);
        }
//        @ApiModelProperty(value = "名称")
        String userAccount = UserLoginRequest.getUserAccount();
//        @ApiModelProperty(value = "密码")
        String userPassword = UserLoginRequest.getUserPassword();

        if (StringUtils.isAllBlank(userAccount, userPassword)) {
            return ResultUtils.error(ErrorCode.PARAM_NOT_NULL);
        }

        User user = userService.userLogin(userAccount, userPassword, request);
//        return new BaseResponse<>(0, user, "登录成功");
        return ResultUtils.success(user);
    }

    /**
     * 管理员查询用户信息
     *
     * @param userName 用户名字
     * @param request  请求体 取session
     * @return 用户信息
     */
    @GetMapping("/search")
    @ApiOperation(value = "管理员查询用户功能")
    public BaseResponse<List<User>> searchUser(@RequestParam String userName,
                                               HttpServletRequest request) {
        if (!isLogin(request)) {
            return ResultUtils.error(ErrorCode.NO_LOGIN);
        }
        // 仅管理员可以访问
        if (!isAdmin(request)) {
            return ResultUtils.error(ErrorCode.NO_AUTH);
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isBlank(userName)) {
            return ResultUtils.error(ErrorCode.PARAM_NOT_NULL, "搜索的用户名为空");
        }
        queryWrapper.like("username", userName);
        List<User> userList = userService.list(queryWrapper);

        List<User> list = userList.stream().map(user -> userService.geySafetyUser(user)).collect(Collectors.toList());
        return ResultUtils.success(list);
    }

    /**
     * 管理员删除用户
     *
     * @param id      用户id
     * @param request 请求体 取session
     * @return boolean
     */
    @GetMapping("/delete")
    @ApiOperation(value = "管理员删除用户功能")
    public BaseResponse<Boolean> deleteUser(@RequestParam Long id, HttpServletRequest request) {
        if (!isLogin(request)) {
            return ResultUtils.error(ErrorCode.NO_LOGIN);
        }
        // 仅管理员可以访问
        if (!isAdmin(request)) {
            return ResultUtils.error(ErrorCode.NO_AUTH);
        }
        // 判断id是否合法
        if (id < 0) {
            return ResultUtils.error(ErrorCode.PARAM_ERROR);
        }
        boolean isSuccess = userService.removeById(id);
        if (!isSuccess) {
            return ResultUtils.error(ErrorCode.PARAM_ERROR, "删除失败(用户可能不存在)");
        }
//        return userService.removeById(id);
        return ResultUtils.success(isSuccess);
    }

    /**
     * 管理员更新用户信息
     *
     * @param request 请求体 取session
     * @return User 脱敏信息
     */
    @GetMapping("/current")
    @ApiOperation(value = "获取当前登录信息")
    public BaseResponse<User> getCurrentUser(HttpServletRequest request) {
        // 取session
        Object userObj = request.getSession().getAttribute(USER_Login_STATE);
        User currentUser = (User) userObj;
        if (currentUser == null) {
            return ResultUtils.error(ErrorCode.NO_LOGIN);
        }
        Long id = currentUser.getId();

        User user = userService.getById(id);

        return ResultUtils.success(user);
    }

    public boolean isLogin(HttpServletRequest request) {
        Object userObj = request.getSession().getAttribute(USER_Login_STATE);
        User currentUser = (User) userObj;
        return currentUser != null;
    }

    /**
     * 判断是否是管理员
     *
     * @param request 请求体 取session
     * @return boolean
     */
    public boolean isAdmin(HttpServletRequest request) {
        // 仅管理员可以访问
        Object userObj = request.getSession().getAttribute(USER_Login_STATE);
        User user = (User) userObj;
        return user != null && user.getUserRole() == ADMIN_ROLE;
    }


    /**
     * 退出登录
     *
     * @param request 请求体
     * @return 退出 1 成功 null 失败
     */
    @PostMapping("/logout")
    @ApiOperation(value = "退出登录")
    public BaseResponse<String> userLogout(HttpServletRequest request) {
        if (request == null) {
            return ResultUtils.error(ErrorCode.NO_LOGIN);
        }
//        return userService.userLogout(request);
        return ResultUtils.success(userService.userLogout(request));
    }


    @PostMapping("/AI/genQuestion")
    @ApiOperation(value = "生成问题")
    public BaseResponse<Boolean> toChat(@RequestBody ProblemGenerationRequest problemGenerationRequest
            , HttpServletRequest request) {
//        if (!isLogin(request)) {
//            return ResultUtils.error(ErrorCode.NO_LOGIN);
//        }


        String ChatId = problemGenerationRequest.getChatId();
        String stage = problemGenerationRequest.getStage();
        int countDirection = problemGenerationRequest.getCount_direction();
        String direction = problemGenerationRequest.getDirection();
        if (StringUtils.isAllBlank(stage, direction)) {
            return ResultUtils.error(ErrorCode.PARAM_NOT_NULL);
        }
        if (countDirection <= 0 || countDirection >= 20) {
            countDirection = 10;
        }
        if (StringUtils.isAllBlank(ChatId)) {
            ChatId = "2394578342";
        }

        return ResultUtils.success(questionService.getQuestion(ChatId, stage, countDirection, direction));
    }


    @GetMapping("/AI/GetAllQuestion")
    @ApiOperation(value = "获取全部问题")
    public BaseResponse<List<Question>> getAllQuestion(int userId) {
        return ResultUtils.success(questionService.getAllQuestion(userId));
    }

}

